<template>
  <div class="container">
    <!-- 预览文章对话框 -->
    <el-dialog
      ref="dialogRef"
      title="预览文章"
      v-loading="loading"
      :visible="showPreviewDialog"
      width="60%"
      @close="handleClose"
      @open="handleOpen"
    >
      <h2>{{ obj.title }}</h2>
      <p>
        <span>{{ obj.createTime | forCreateTime }}</span>
        &nbsp;
        <span>{{ obj.creatorID | formatCreator }}</span>
        &nbsp;
        <span> <i class="el-icon-view"></i>&nbsp; {{ obj.visits }}</span>
      </p>
      <div class="articlebody" v-html="obj.articleBody"></div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { detail } from '@/api/hmmm/articles.js'
import object from '@/api/base/baseApi.js'
export default {
  props: {
    showPreviewDialog: {
      type: Boolean,
      default: false
    },
    articleId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      obj: {
        title: '',
        createTime: '',
        creatorID: '',
        visits: '',
        articleBody: ''
      },
      loading: false
    }
  },
  // 日期格式化--过滤器
  filters: {
    forCreateTime: (value) => {
      return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    },
    formatCreator: (val) => {
      const { role } = object
      const valString = '' + val
      const res = role.find(item => item.id === valString)
      return res ? res.value : '未知'
    }
  },
  methods: {
    // 关闭对话框
    handleClose () {
      this.$emit('update:showPreviewDialog', false)
      this.obj = {
        title: '',
        createTime: '',
        creatorID: '',
        visits: '',
        articleBody: ''
      }
    },
    // 打开对话框
    handleOpen () {
      this.$emit('update:showPreviewDialog', true)
      // 打开对话框才获取文章详情
      this.getArticleDetails()
    },
    // 获取文章详情
    async getArticleDetails () {
      this.loading = true
      const res = await detail({
        id: this.articleId,
        ...this.obj
      })
      this.obj = res.data
      this.loading = false
    }
  }
}
</script>

<style scoped lang='scss'>
.articlebody {
  width: 100%;
  min-height: 20px;
  padding: 20px 15px;
  border-top: 1px dashed rgb(49, 46, 46);
  background-color: rgba(221, 234, 238, 0.931);
}
</style>
